//
//  WorkflowDetailViewController.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 2017/8/30.
//  Copyright © 2017年 com.xtion.crm. All rights reserved.
//

#import "WorkflowDetailViewController.h"
#import "FootButtonContainView.h"
#import "CommnetMessageSendPanel.h"
#import "WorkflowSelectUserViewController.h"
#import "FunctionMenu.h"
#import "WorkflowHistoryViewController.h"

NSString *const WorkflowDetailViewControllerListDicDataParametersParamKey = @"WorkflowDetailViewControllerListDicDataParametersParamKey";

@interface WorkflowDetailViewController ()<FootButtonContainViewDelegate,CommnetMessageSendPanelDelegate,FunctionMenuDelegate>
{
    NSDictionary *_queryDic;
    WorkflowApplyInfo *_workApplyInfo;
    CommonObjInfo *_commonObjInfo;
    
    FootButtonContainView *_footContainView;
    XUIGroupTableView *_gtable;
    
    CommnetMessageSendPanel *_sendPanel;
    NSString *_tipMsg;
    PermissionType _permissionType;
    
    RSWDataOperation *_manager;
    
    FunctionMenu *_functionMenu;
    BOOL _foldMenu;
}
@end

@implementation WorkflowDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color];
    [self checkSession];
    
    [self initVariable];
    
    [_manager getWorkflowApprove:_queryDic[ProcessCode]
                      customform:_queryDic[CustomForm]
                         version:_queryDic[Version]
                      instanceid:_queryDic[InstanceId]
                      completion:^(NSInteger nResult, id output, NSError *error) {
        [self requestComplete:nil result:nResult output:output error:error];
    }];
}

-(void)viewControllerWillDealloc
{
    [super viewControllerWillDealloc];
    
    [_manager terminateRequest];
    
    [self removeObserver];
}

-(void)initVariable
{
    _gtable = [_core getGrouptableView];
    _commonObjInfo = [CommonObjInfo emptyCommonObjInfo];
    
    _vclType = DynamicColumnFieldViewTypeModify;
    _transformMap = [CommonObjInfo JSONObjectProperty:nil];
    
    [super initViewDidLoad];
    
    _queryDic = self.param[WorkflowDetailViewControllerListDicDataParametersParamKey];
    [self setBackNavigateItemTitle:[_queryDic valueForKey:ProcessName] rightItemImageName:@"nav_btn_more"];
    
    _manager = [[RSWDataOperation alloc]initWithDataOperationManagerDelegate:self];
    
    _foldMenu = NO;
    
    [self addKeyboardObserver];
}

-(void)initMenu
{
    _functionMenu = [[FunctionMenu alloc]initWithParentView:self.view menuItemCountPerRow:3];
    _functionMenu.delegate = self;
    
    [_functionMenu addMenuItemWithText:@"流程历史" image:[UIImage imageNamed:@"functionmenu_workflow"] andTag:@"1"];
}

-(void)iniFootContainView
{
    if(_footContainView != nil)
    {
        _gtable.height += _footContainView.frame.size.height;
        [_footContainView removeFromSuperview];
        _footContainView = nil;
    }
    
    if(_footContainView == nil)
    {
        _footContainView = [FootButtonContainView new];
        _footContainView.delegate = self;
    }
    
    NSMutableArray *i = [NSMutableArray new];
    
    if(_workApplyInfo.isMyPendingTask == YES)
    {
        if(_workApplyInfo.permission.approve == YES)
        {
            FootButtonItem *item = [FootButtonItem new];
            item.tag = @"0";
            item.backgroundColor = [UIColor whiteColor];
            item.titleColor = [UIColor redColor];
            item.title = _workApplyInfo.permission.nextActionNames[0];
            [i addObject:item];
        }
    }
    if(_workApplyInfo.permission.withdrawProcess == YES)
    {
        FootButtonItem *item = [FootButtonItem new];
        item.tag = @"1";
        item.backgroundColor = [UIColor whiteColor];
        item.titleColor = [UIColor redColor];
        item.title = @"撤销";
        [i addObject:item];
    }
    if(_workApplyInfo.permission.sendBackProcess == YES)
    {
        FootButtonItem *item = [FootButtonItem new];
        item.tag = @"2";
        item.backgroundColor = [UIColor whiteColor];
        item.titleColor = [UIColor blackColor];
        item.title = @"退回";
        [i addObject:item];
    }
    if(_workApplyInfo.permission.discardProcess == YES)
    {
        FootButtonItem *item = [FootButtonItem new];
        item.tag = @"3";
        item.backgroundColor = [UIColor whiteColor];
        item.titleColor = [UIColor redColor];
        item.title = @"废弃";
        [i addObject:item];
    }
    if(_workApplyInfo.permission.reverseProcess == YES)
    {
        FootButtonItem *item = [FootButtonItem new];
        item.tag = @"4";
        item.backgroundColor = [UIColor whiteColor];
        item.titleColor = [UIColor redColor];
        item.title = @"返签";
        [i addObject:item];
    }
    if(_workApplyInfo.permission.signTogether == YES)
    {
        FootButtonItem *item = [FootButtonItem new];
        item.tag = @"5";
        item.backgroundColor = [UIColor whiteColor];
        item.titleColor = [UIColor redColor];
        item.title = @"会签";
        [i addObject:item];
    }
    if(i.count > 0)
    {
        _gtable.height -= _footContainView.frame.size.height;
        _footContainView.item = i;
        
        [self.view addSubview:_footContainView];
        _footContainView.bottom = self.view.bottom;
        _footContainView.backgroundColor = [UIColor whiteColor];
    }
}

-(void)requestComplete:(XMSDataOperationManager *)dom result:(NSInteger)nResult output:(id)output error:(NSError *)error
{
    [self filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
     {
         switch(requestResult)
         {
             case YES:
             {
                 _workApplyInfo = output;
                 if(_workApplyInfo.fields.count > 0)
                 {
                     _constraint = [WorkAppInfo constraint:_workApplyInfo];
                     
                     _commonObjInfo.expandfields = [_workApplyInfo.modelValue mutableCopy];
                     if(_workApplyInfo.attachments.count > 0)
                         [_commonObjInfo.expandfields setObject:_workApplyInfo.attachments forKey:Field_Attachment];
                     
                     _packObj = _commonObjInfo;
                     
                     [super reloadDyanmicField];
                     [self iniFootContainView];
                     [self initMenu];
                 }
                 break;
             }
             default:
             {
                 break;
             }
         }
     }];
}

#pragma mark -- FootButtonContainViewDelegate

-(void)footButtonContainView:(FootButtonContainView *)view clickedItemWithTag:(NSString *)tag
{
    NSString *title = @"";
    for(FootButtonItem *btn in view.item)
    {
        if([btn.tag isEqualToString:tag] == YES)
        {
            title = btn.title;
            break;
        }
    }
    
    if([title isEqualToString:@"撤销"])
    {
        _tipMsg = [NSString stringWithFormat:@"%@原因",title];
        
        if(_sendPanel == nil)
        {
            _sendPanel = [[CommnetMessageSendPanel alloc]initWithFrame:CGRectMake(0, self.view.height, self.view.width, 44)];
            _sendPanel.textView.placeholder = _tipMsg;
            _sendPanel.delegate = self;
            [self.view addSubview:_sendPanel];
        }
        
        [_sendPanel becomeFirstResponder];
        _permissionType = PermissionTypeWithdraw;
        
        return;
    }
    else if([title isEqualToString:@"退回"])
    {
        _tipMsg = [NSString stringWithFormat:@"%@原因",title];
     
        if(_sendPanel == nil)
        {
            _sendPanel = [[CommnetMessageSendPanel alloc]initWithFrame:CGRectMake(0, self.view.height, self.view.width, 44)];
            _sendPanel.textView.placeholder = _tipMsg;
            _sendPanel.delegate = self;
            [self.view addSubview:_sendPanel];
        }
        
        [_sendPanel becomeFirstResponder];
        _permissionType = PermissionTypeSendBack;
        
        return;
    }
    else if([title isEqualToString:@"废弃"])
    {
        _tipMsg = [NSString stringWithFormat:@"%@原因",title];
        
        if(_sendPanel == nil)
        {
            _sendPanel = [[CommnetMessageSendPanel alloc]initWithFrame:CGRectMake(0, self.view.height, self.view.width, 44)];
            _sendPanel.textView.placeholder = _tipMsg;
            _sendPanel.delegate = self;
            [self.view addSubview:_sendPanel];
        }
        
        [_sendPanel becomeFirstResponder];
        _permissionType = PermissionTypeDiscard;
        return;
    }
    else if([title isEqualToString:@"返签"])
    {
        _tipMsg = [NSString stringWithFormat:@"%@原因",title];
        
        if(_sendPanel == nil)
        {
            _sendPanel = [[CommnetMessageSendPanel alloc]initWithFrame:CGRectMake(0, self.view.height, self.view.width, 44)];
            _sendPanel.textView.placeholder = _tipMsg;
            _sendPanel.delegate = self;
            [self.view addSubview:_sendPanel];
        }
        
        [_sendPanel becomeFirstResponder];
        _permissionType = PermissionTypeReverse;
        return;
    }
    else if([title isEqualToString:@"会签"])
    {
        //TODO
        return;
    }
    else
    {
        if([super verifyDynamicField:_constraint] == YES)
        {
            CommonObjInfo *modelInfo = [CommonObjInfo new];
            
            [modelInfo.expandfields setValue:_workApplyInfo.customForm.customerFormId forKey:@"Slickflow_CustomForm2ID"];
            [modelInfo.expandfields setValue:_workApplyInfo.version forKey:@"Slickflow_Version"];
            [modelInfo.expandfields setValue:_workApplyInfo.processGUID forKey:@"Slickflow_ProcessGUID"];
            [modelInfo.expandfields setValue:_queryDic[ProcessCode] forKey:@"Slickflow_ProcessCode"];
            
            //下一步提交按钮
            [modelInfo.expandfields setValue:_workApplyInfo.permission.nextActionNames[0] forKey:@"Button"];
            
            [super extractDynamicFieldValue:_constraint transformMap:_transformMap packObj:modelInfo specialExtract:^BOOL(FieldDescript *fixField)
             {
                 return NO;
             }];
            
            XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
            
            NSMutableDictionary *dic = [NSMutableDictionary new];
            NSString *appInstanceId = modelInfo.expandfields[@"ID"];
            [dic setValue:appInstanceId forKey:@"AppInstanceID"];
            [dic setValue:_queryDic[ProcessName] forKey:@"AppName"];
            [dic setValue:modelInfo.expandfields forKey:@"Conditions"];
            [dic setValue:[[MyInfo myInfo].userNumber toNSString] forKey:@"CreateUserID"];
            [dic setValue:[MyInfo myInfo].userName forKey:@"CreateUserName"];
            [dic setValue:@"#NEXT#" forKey:@"NextActivityPerformers"];
            [dic setValue:_workApplyInfo.processGUID forKey:@"ProcessGUID"];
            [dic setValue:[[MyInfo myInfo].userNumber toNSString] forKey:@"UserID"];
            [dic setValue:[MyInfo myInfo].userName forKey:@"UserName"];
            [dic setValue:_workApplyInfo.version forKey:@"Version"];
            [dic setValue:@(0) forKey:@"themeColor"];
            [dic setValue:_workApplyInfo.attachments forKey:@"attachment"];
            
            p.param[WorkflowSelectUserViewControllerFormDicParametersParamKey] = dic;
            p.param[WorkflowSelectUserViewControllerOptTypeParametersParamKey] = @(WorkflowOptTypeAudit);
            [XUINavigationController pushViewControllerClass:[WorkflowSelectUserViewController class] withSwitchParam:p];
        }
    }
}

- (CGFloat)dynamicColumnFieldCore:(DynamicColumnFieldCore *)dynamicColumnFieldCore heightForHeaderInGroup:(NSInteger)group
{
    return 0;
}

#pragma mark --
#pragma mark -- send reply

- (void)commnetMessageSendPanelSendText:(CommnetMessageSendPanel *)panel
{
    if(_sendPanel.textView.text.length <=0 || [_sendPanel.textView.text isBlankString] )
    {
        [UIAlertView showInfoMsg:[NSString stringWithFormat:@"请输入%@",_tipMsg]];
        return;
    }
    
    [_sendPanel resignFirstResponder];
    
    switch (_permissionType) {
        case PermissionTypeWithdraw:
            [self withDraw];
            break;
        case PermissionTypeSendBack:
            [self sendBack];
            break;
        case PermissionTypeDiscard:
            [self discard];
            break;
        case PermissionTypeReverse:
            [self reverse];
            break;
        default:
            break;
    }
}

#pragma mark -- 
#pragma mark -- private method

-(void)withDraw
{
    [_manager withDrawWorkflowAppInstance:_queryDic[ProcessCode]
                                  version:_queryDic[Version]
                                  comment:_sendPanel.textView.text
                                  modelid:_workApplyInfo.modelValue[@"ID"]
                               completion:^(NSInteger nResult, BOOL bReslut, NSError *error)
     {
         [super filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
          {
              switch (nResult)
              {
                  case YES:
                  {
                      if(bReslut == YES)
                      {
                          [XUIAlertView alertViewWithTitle:@"提示" message:@"提交成功" cancelButtonTitle:nil otherButtonTitles:@[@"确定"] clickBlock:^(NSInteger nClickindex)
                           {
                                [XUINavigationController pop];
                           }];
                      }
                      else
                      {
                          if(error.domain.length > 0)
                              [UIAlertView showErrorMsg:error.domain];
                          else
                              [UIAlertView showErrorMsg:@"提交失败"];
                      }
                      
                      break;
                  }
                  default:
                  {
                      [UIAlertView showErrorMsg:@"提交失败"];
                      break;
                  }
              }
          }];
     }];
}

-(void)sendBack
{
    [_manager sendBackWorkflowAppInstance:_queryDic[ProcessCode]
                                  version:_queryDic[Version]
                                  comment:_sendPanel.textView.text
                                  modelid:_workApplyInfo.modelValue[@"ID"]
                               completion:^(NSInteger nResult, BOOL bReslut, NSError *error)
     {
         [super filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
          {
              switch (nResult)
              {
                  case YES:
                  {
                      if(bReslut == YES)
                      {
                          [XUIAlertView alertViewWithTitle:@"提示" message:@"提交成功" cancelButtonTitle:nil otherButtonTitles:@[@"确定"] clickBlock:^(NSInteger nClickindex)
                           {
                               [XUINavigationController pop];
                           }];
                      }
                      else
                      {
                          if(error.domain.length > 0)
                              [UIAlertView showErrorMsg:error.domain];
                          else
                              [UIAlertView showErrorMsg:@"提交失败"];
                      }
                      
                      break;
                  }
                  default:
                  {
                      [UIAlertView showErrorMsg:@"提交失败"];
                      break;
                  }
              }
          }];
     }];
}

-(void)discard
{
    [_manager discardWorkflowAppInstance:_queryDic[ProcessCode]
                                  version:_queryDic[Version]
                                  comment:_sendPanel.textView.text
                                  modelid:_workApplyInfo.modelValue[@"ID"]
                               completion:^(NSInteger nResult, BOOL bReslut, NSError *error)
     {
         [super filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
          {
              switch (nResult)
              {
                  case YES:
                  {
                      if(bReslut == YES)
                      {
                          [XUIAlertView alertViewWithTitle:@"提示" message:@"提交成功" cancelButtonTitle:nil otherButtonTitles:@[@"确定"] clickBlock:^(NSInteger nClickindex)
                           {
                               [XUINavigationController pop];
                           }];
                      }
                      else
                      {
                          if(error.domain.length > 0)
                              [UIAlertView showErrorMsg:error.domain];
                          else
                              [UIAlertView showErrorMsg:@"提交失败"];
                      }
                      
                      break;
                  }
                  default:
                  {
                      [UIAlertView showErrorMsg:@"提交失败"];
                      break;
                  }
              }
          }];
     }];
}


-(void)reverse
{
    [_manager reverseWorkflowAppInstance:_queryDic[ProcessCode]
                                  version:_queryDic[Version]
                                  comment:_sendPanel.textView.text
                                  modelid:_workApplyInfo.modelValue[@"ID"]
                               completion:^(NSInteger nResult, BOOL bReslut, NSError *error)
     {
         [super filterRequestResult:nResult defaultError:error noFilter:^(NSInteger requestResult)
          {
              switch (nResult)
              {
                  case YES:
                  {
                      if(bReslut == YES)
                      {
                          [XUIAlertView alertViewWithTitle:@"提示" message:@"提交成功" cancelButtonTitle:nil otherButtonTitles:@[@"确定"] clickBlock:^(NSInteger nClickindex)
                           {
                               [XUINavigationController pop];
                           }];
                      }
                      else
                      {
                          if(error.domain.length > 0)
                              [UIAlertView showErrorMsg:error.domain];
                          else
                              [UIAlertView showErrorMsg:@"提交失败"];
                      }
                      
                      break;
                  }
                  default:
                  {
                      [UIAlertView showErrorMsg:@"提交失败"];
                      break;
                  }
              }
          }];
     }];
}

#pragma mark --
#pragma mark -- keyBoard observer

- (BOOL)keyboardWillShow:(NSNotification *)noti
{
    BOOL bResult = [super keyboardWillShow:noti];
    if (YES == bResult)
    {
        double duration = [(NSNumber *) [[noti userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        NSInteger curve = [(NSNumber *) [[noti userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
        [UIView animateWithDuration:duration delay:0 options:curve animations:^
         {
             _sendPanel.bottom = self.view.height - self.keyboardOffSet;
             
         } completion:^(BOOL finished)
         {
         }];
    }
    return bResult;
}

- (BOOL)keyboardWillHide:(NSNotification *)noti
{
    BOOL bResult = [super keyboardWillHide:noti];
    if(YES == bResult)
    {
        double duration = [(NSNumber *) [[noti userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
        NSInteger curve = [(NSNumber *) [[noti userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
        [UIView animateWithDuration:duration delay:0 options:curve animations:^
         {
             _sendPanel.top = self.view.height;
             
         }completion:^(BOOL finished)
         {
         }];
    }
    return bResult;
}

- (void)keyboardWillChangeSize:(CGFloat)changeSize withAnimationDuration:(CGFloat)duration curve:(UIViewAnimationCurve)curve
{
    [UIView animateWithDuration:0.25 animations:^
     {
         _sendPanel.top += changeSize;
     }];
}

#pragma mark --
#pragma mark -- scroll delegate

-(void)groupTableViewWillBeginDragging:(XUIGroupTableView *)groupTableView;
{
    [_sendPanel resignFirstResponder];
}

#pragma mark ---
#pragma mark functionMenu delegate

-(void)functionMenu:(FunctionMenu *)functionMenu clickTag:(NSString *)tag
{
    [self showOrCloseFunctionMenu:NO];
    
    switch([tag intValue])
    {
        case 1:
        {
            XUIViewControllerSwitchParam *p = [XUIViewControllerSwitchParam new];
            
            p.param[WorkflowHistoryViewControllerModelIdParamKey] = _workApplyInfo.modelValue[@"ID"];
            
            [XUINavigationController pushViewControllerClass:[WorkflowHistoryViewController class] withSwitchParam:p];

            break;
        }
    }
}

-(void)functionMenu:(FunctionMenu *)functionMenu touchEmpty:(id)sender
{
    [self clickedRightBarButton:nil];
}

-(void)showOrCloseFunctionMenu:(BOOL)show
{
    if(_foldMenu == show)
        return;
    
    [UIViewController closeKeyBoard];
    
    _foldMenu = show;
    
    if(_foldMenu == YES)
    {
        [_functionMenu show];
    }
    else
    {
        [_functionMenu dismiss];
    }
}

#pragma mark --
#pragma mark -- submit data

-(void)clickedRightBarButton:(id)sender
{
   [self showOrCloseFunctionMenu:!_foldMenu];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
